<template>
  <jke-modal
    :width="1200"
    :visible.sync="jkeForm.visible"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <div class="form-body" :style="{ height: jkeForm.fullscreen ? 'calc(100vh - 110px)' : 'auto' }">
      <a-card title="基础信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="出库单编号">
            <a-input v-decorator="['entryCode']" :maxLength="21" placeholder="请输入，不输入则自动生成" />
          </a-form-item>
          <a-form-item label="出库类型" required>
            <a-select
              show-search
              v-decorator="[
                'outWarehouseType',
                {
                  rules: [
                    {
                      required: true,
                      message: '请选择出库类型',
                    },
                  ],
                },
              ]"
              class="row-input"
              placeholder="请选择"
              allowClear
              :filter-option="filterOption"
              @change="changeInType"
            >
              <a-select-option :value="item.itemValue" v-for="item in outWarehouseType" :key="item.itemValue">
                {{ item.itemText }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="领出人">
            <j-select-user-by-dep
              :multi="false"
              v-decorator="['receiverPersion']"
              @changeRow="(a, b, c) => onChangeUser(b || {}, item.searchIndex)"
            ></j-select-user-by-dep>
          </a-form-item>
        </a-form>

        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="出库时间" required>
            <a-date-picker
              v-decorator="[
                'outWarehouseTimeText',
                {
                  rules: [
                    {
                      required: true,
                      message: '请选择出库时间',
                    },
                  ],
                },
              ]"
              :defaultValue="getCurrentData"
              format="YYYY-MM-DD HH:mm"
              mode="time"
              style="width: 100%"
              @change="operaChange"
            />
            <a-input v-decorator="['outWarehouseTime']" type="hidden" placeholder="请选择" />
          </a-form-item>

          <a-form-item
            label="销售订单"
            v-show="form.getFieldValue('outWarehouseType') && form.getFieldValue('outWarehouseType') == 0"
          >
            <a-input
              @click="outopenIt"
              v-decorator="['saleOrderCode']"
              placeholder="请选择"
              :read-only="true"
              :class="form.setFieldsValue('saleOrderCode') ? 'has-value' : ''"
            >
              <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
              <a-icon
                slot="suffix"
                type="close-circle"
                theme="filled"
                class="close-icon"
                @click="getSaleSelectValue(false, '', [])"
              />
            </a-input>
            <a-input v-decorator="['saleOrderId']" type="hidden" placeholder="请选择" />
          </a-form-item>
          <a-form-item></a-form-item>
        </a-form>
      </a-card>
      <createFormItem ref="createFormItemRef" :formType="5" />

      <a-card title="出库物品明细" :bordered="false" style="margin-top: 12px; margin-bottom: 12px; flex: 1">
        <a-col :span="24" style="margin-bottom: 38px">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="processTable.loading"
            :rowNumber="true"
            rowNumberText="序号"
            :columns="processTable.columns"
            :dataSource="processTable.dataSource"
            :maxHeight="300000"
            :disabled="formDisabled"
            :actionButton="true"
            @valueChange="valueChange"
            :rowSelection="true"
            :addActionButton="false"
            :delActionBtn="false"
          >
            <div slot="options" style="display: flex; justify-content: space-between; margin-bottom: 10px">
              <a-button
                @click="openItProcess"
                type="primary"
                icon="plus"
                style="margin-right: 10px; border-radius: 4px; height: 32px; width: 76px"
                >添加
              </a-button>
              <a-button
                @click="handleConfirmDelete"
                type="primary"
                icon="minus"
                style="border-radius: 4px; margin-right: 8px"
                >删除
              </a-button>
              <PubImport
                ref="PubImport"
                tableCode="MESS_PRODUCT_FLOW"
                modelName="出库物品明细导入模板"
                @getImportData="getImportData"
                :formType="'10'"
                style="margin-right: 10px"
              />
            </div>
            <template v-slot:processCodeName="props">
              <a-input
                @click="openItProcess(props)"
                :value="props.value"
                placeholder="请选择"
                :read-only="true"
                :class="props.value ? 'has-value' : ''"
              >
                <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
                <a-icon
                  slot="suffix"
                  type="close-circle"
                  theme="filled"
                  class="close-icon"
                  @click="getSelectValueProcess(false, '', [], props.rowId)"
                />
              </a-input>
            </template>
            <template v-slot:processWorkRate="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                @input="(e) => inputNums(props, e, 'processWorkRate', 'processTable')"
              />
            </template>
            <template v-slot:excessWorkRate="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                @input="(e) => inputNums(props, e, 'excessWorkRate', 'processTable')"
              />
            </template>
            <template v-slot:processRequire="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                :maxLength="500"
                @input="(e) => inputRequire(props, e, 'processRequire', 'processTable')"
              />
            </template>
            <template v-slot:action="props">
              <a-popconfirm
                title="是否删除?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(props)"
                @cancel="cancel"
              >
                <a style="padding-left: 3px; color: #f25643">删除</a>
              </a-popconfirm>
            </template>
          </j-editable-table>
        </a-col>
      </a-card>
    </div>
    <div class="footer-submit" :class="jkeForm.fullscreen ? 'form-footer' : ''">
      <a-button @click="closeBtn" class="submitBtn" style="margin-right: 10px"> 取消</a-button>
      <a-button type="primary" :loading="loadingSubmit" class="submitBtn" @click="saveForm()"> 提交</a-button>
    </div>
    <tableSelect ref="tableSelect" @getSelectValue="getSelectValue">
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <a-form-model ref="ruleForm" layout="inline">
          </a-form-model>
        </div>
      </div>
    </tableSelect>
    <tableSelect
      ref="tableSelectProcess"
      @getSelectValue="getSelectValueProcess"
      :key="indexProcess"
      @cancel="searchResetProcess"
    >
      <div slot="head">
        <div class="uni-card" style="background: #fff">
        </div>
      </div>
    </tableSelect>
    <!-- 销售订单 -->
    <goodsTableSelect ref="SaleSelect" @getSelectValue="getSaleSelectValue" :showType="false"></goodsTableSelect>
  </jke-modal>
</template>
<script>
import { FormTypes } from '@/utils/JEditableTableUtil'
import crumbs from '@/components/crumbs.vue'
import { getFileListByIds } from '@/api/api'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import { apiBaseUrlDownload } from '@/utils/request'
import { APILX } from '@/api/requestLx'
import { validateDuplicateValue } from '@/utils/util'
import { fourFloatNum, accMul, accDivMin } from '@/utils/util'
import Examine from '@/components/examine'
import tableSelect from '@/components/tableSelect'
import PubImport from '@/components/pubBtn/PubImport.vue'
import goodsTableSelect from '@/components/goodsTableSelect'
import moment from 'moment'

import {
  queryOptionList,
  inventoryApi,
} from '@/api/productOrder'
import { goodsColumns, outopenItcolumns, goodsSelectColumns } from './column.js'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import createFormItem from '@/components/createForm.vue'

export default {
  name: 'customerForm', //新建客户
  data() {
    return {
      jkeForm: {
        title: '新建单位',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      indexProcess: 0.2,
      outopenItcolumns: outopenItcolumns,

      processDataVo: '',
      sendType: '',
      isLoading: false, //防止tab来回切换 导致数据重复渲染
      tabNor: '待盘点（0）',
      tabAbNor: '已盘点（0）',
      addOrEdit: true, //待盘点 true 已盘点false
      inventoryUserIdText: '',
      inventoryUserIdRealId: '',
      signUser: '', //盘点人 id
      warehouseIdEdit: '', //继续盘点 仓库ID
      domianURL: apiBaseUrlDownload, //表格图片展示
      getGoodsId: '', //选仓库取到的id
      //新建时候 获取明细
      inventoryTypeList: [], //盘点类型下拉
      warehouseIdList: [], //仓库数据下拉
      selectRowKeys: [],
      selectRowKeysEd: [],
      selectGoodsIds: [],
      selectGoodsIdsEd: [],
      validateDuplicateValue, //自动生成编码
      queryId: '',
      loadingSubmit: false, //防止多次提交
      submitApi: APILX.warehouseOutboundOrderInfoAdd,
      queryParam: {},
      isEdit: false,
      mainDivWidth: 0,
      attachment: '', //附件
      form: this.$form.createForm(this, { name: 'coordinated' }),
      reloadForm: false,
      unitLists: [],
      outWarehouseType: [],
      formTypeExtendedFields: [],
      refKeys: ['processTable'],
      processTable: {
        loading: false,
        dataSource: [],
        columns: [],
      },
    }
  },
  components: {
    FileUpload,
    Examine,
    crumbs,
    tableSelect,
    JEditableTable,
    createFormItem,
    PubImport,
    goodsTableSelect,
  },
  created() {
    this.getUnitList()
  },
  mounted() {
    let mainDiv = document.querySelector('.ant-layout-content') //ant-layout-content
    this.mainDivWidth = `${mainDiv.clientWidth}px`
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    getCurrentData() {
      return moment().format('YYYY-MM-DD HH:mm:ss')
    },
  },
  methods: {
    changeInType(e) {
      // 切换入库类型，清空关联数据
      this.processTable.dataSource = []
      if (e != 1) {
        this.form.setFields({
          produceOrderId: '',
          produceOrderName: '',
        })
      } else if (e != 0) {
        this.form.setFields({
          saleOrderCode: '',
          saleOrderId: '',
        })
      }
    },
    async getExtended() {
      let res = await APILX.formTypeExtendedFieldList({ formType: 2 })
      if (res.code == 200 && res.result) {
        let formTypeExtendedFields = res.result
        let columns = []
        console.log(formTypeExtendedFields,'formTypeExtendedFields')
        formTypeExtendedFields.forEach((fields) => {
          let tableHead = {
            title: fields.fieldName,
            dataIndex: 'extDataJson.' + fields.fieldKey,
            ellipsis: true,
            width: 150,
            searchIndex: 'extDataJson.' + fields.fieldKey,
            scopedSlots: {
              filterDropdown: 'searchDropdown',
              filterIcon: 'searchIcon',
            },
          }
          columns.push(tableHead)
        })
        this.outopenItcolumns = [...this.outopenItcolumns, ...columns]
      }
    },
    async outopenIt() {
      let par = {}
      par = {
        list: '/sale/saleOrderInfo/list',
        visible: true, //弹窗开启
        title: '销售订单', //标题名称
        multi: false, //是否多选
        columns: this.outopenItcolumns, //表格配置
        value: this.form.getFieldValue('saleOrderId'), //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: '订单编号', //回显的中文，如：'张三'
        textKey: 'orderCode', //回显的中文key
        action: 'post',
      }
      this.$refs.SaleSelect.getInit(par)
    },
    getSaleSelectValue(id, text, item) {
      if (!id) {
        this.form.setFieldsValue({
          saleOrderCode: '',
          saleOrderId: '',
        })
        this.processTable.dataSource = []
        return
      }
      this.Selectindex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      if (this.form.getFieldValue('outWarehouseType') == 0) {
        this.form.setFieldsValue({
          saleOrderCode: item[0].orderCode,
          saleOrderId: id,
        })
        API.getSaleOrderDetail({ orderId: id }).then((res) => {
          if (res.code == 200) {
            let list = res.result.records
            let arr = []
            list.forEach((el) => {
              arr.push({ ...el, id: el.bsiId, inWarehouseNum: el.maxQualifiedNum })
            })
            this.processTable.dataSource = [...arr]
          } else {
            this.$antdMessage.error(res.message)
          }
        })
      }
    },
    getImportData(data) {
      let list = JSON.parse(JSON.stringify(this.processTable.dataSource))
      const { error, values: tableValues } = this.$refs.processTable.getValuesSync({ validate: true })
      let realList = []
      list.forEach((item) => {
        tableValues.map((i) => {
          if (i.id == item.id) {
            realList.push(item)
          }
        })
      })
      console.log(' alist', realList)
      data.forEach((item) => {
        ;(item.inWarehouseNum = item.num),
          (item.serialSpecifications = item.serialSpecifications || '-'),
          (item.unitName = item.unitName || '-')
      })
      this.processTable.dataSource = [...list, ...data]
    },
    onChangeUser(v, index) {
      this.queryParam[index] = v
        .map((e) => {
          return e.id
        })
        .toString()
      this.queryParam[`${index}realname`] = v
        .map((e) => {
          return e.realname
        })
        .toString()
      this.queryParam[`${index}username`] = v
        .map((e) => {
          return e.username
        })
        .toString()
    },
    getSelectValueProcess(id, text, item, rowId) {
      item.forEach((e) => {
        e.serialCode = e.serialNumber
        e.serialNumber = ''
        this.$refs.processTable.push({
          ...e,
        })
      })
    },
    searchResetProcess() {
      this.$refs.tableSelectProcess.searchReset()
    },
    searchProcess() {
      this.$refs.tableSelectProcess.searchQuery(this.filterFormProcess)
    },
    handleConfirmDelete() {
      this.$refs.processTable.handleConfirmDelete()
    },
    openItProcess(props) {
      let par = {
        list: '/basicserial/basicSerialInfo/list',
        visible: true, //弹窗开启
        title: '出库单详情列表', //标题名称
        multi: true, //是否多选
        columns: goodsSelectColumns, //表格配置
        value: this.goodsValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.goodsText, //回显的中文，如：'张三'
        textKey: 'serialName', //回显的中文key
        action: 'post',
      }
      this.$refs.tableSelectProcess.getInit(par)
    },
    minMax(value, callback) {
      console.log(value, this.form.getFieldValue('inventoryMax'))
      if (parseFloat(value) > parseFloat(this.form.getFieldValue('inventoryMax'))) {
        callback('true')
        return false
      }
      callback()
    },
    parseNumber(field) {
      let value = this.form.getFieldValue(field)
      console.log(value)

      // 解析用户输入的值
      if (value === '') {
        return 0
      }
      // 去除非数字和小数点的字符
      const newValue = value.replace(/[^\d.]/g, '')
      // 分割整数和小数部分
      const parts = newValue.split('.')
      // 获取整数和小数部分的值
      let integer = parts[0]
      let decimal = parts[1]
      // 限制整数部分最多4位
      // if (integer.length > 4) {
      //   integer = integer.slice(0, 4)
      // }
      // 限制小数部分最多4位
      if (decimal && decimal.length > 4) {
        decimal = decimal.slice(0, 4)
      }
      // 拼接整数和小数部分
      let parsedValue = integer
      if (newValue.includes('.')) {
        parsedValue += '.'
      }
      if (decimal) {
        parsedValue += decimal
      }

      let values = {}
      values[field] = parsedValue
      console.log(values)
      this.form.setFieldsValue(values)
      // 将解析后的值转为数字类型
      return ''
    },
    maxMin(value, callback) {
      if (parseFloat(value) < parseFloat(this.form.getFieldValue('inventoryMin'))) {
        callback('true')
        return false
      }
      callback()
    },
    getUnitList() {
      APILX.basicUnitList({ pageNo: 1, pageSize: 9999 }).then(({ result }) => {
        this.unitLists = result.records
      })
    },
    operaChange(a, b) {
      this.form.setFieldsValue({ outWarehouseTime: a.format('YYYY-MM-DD HH:mm') })
      this.$forceUpdate()
    },
    parseVNumber(validType, value, id, column, callback) {
      console.log('valuesss', value)
      // 解析用户输入的值
      if (value === '') {
        callback(false, '只能输入大于0的，最多16位，小数点后4位')
        console.log('valuesss', 12345)

        return false
      }
      if (value <= 0) {
        callback(false, '只能输入大于0的，最多16位，小数点后4位')
        console.log('valuesss', 123)

        return false
      }
      // 去除非数字和小数点的字符
      const newValue = value.replace(/[^\d.]/g, '')
      // 分割整数和小数部分
      const parts = newValue.split('.')
      // 获取整数和小数部分的值
      let integer = parts[0]
      let decimal = parts[1]
      // 限制整数部分最多16位
      if (integer.length > 16) {
        // integer = integer.slice(0, 16)
        callback(false, '只能输入大于0的，最多16位，小数点后4位')
        return false
      }
      // 限制小数部分最多4位
      if (decimal && decimal.length > 4) {
        callback(false, '只能输入大于0的，最多16位，小数点后4位')
        console.log('valuesss', 4)

        return false
        decimal = decimal.slice(0, 4)
      }

      // 将解析后的值转为数字类型
      callback(true)

      return true
    },
    getDic() {
      APILX.warehouseOutboundOrderInfoEntryType().then((res) => {
        this.outWarehouseType = JSON.parse(JSON.stringify(res.result))
      })
      //出入库明细List
      APILX.formTypeExtendedFieldList({ formType: 6 }).then((res) => {
        if (res.code == 200 && res.result) {
          let formTypeExtendedFields = res.result || []
          let columns = [
            {
              title: '数量',
              key: 'serialNumber',
              width: '13%',
              isrequired: true,
              ellipse: true,
              placeholder: '请输入',
              type: FormTypes.inputNumber,
              validateRules: [
                {
                  required: true, // 必填
                  message: `数量不能为空`, // 提示的文本
                },
                {
                  handler: this.parseVNumber,
                  message: `只能输入大于0的，最多16位，小数点后4位`, // 提示的文本
                },
              ],
            },
          ]
          formTypeExtendedFields.forEach((field) => {
            let col = {
              title: field.fieldName,
              key: 'extDataJson.' + field.fieldKey,
              type: FormTypes.input,
              placeholder: field.placeholder,
              width: '15%',
            }
            if (field.fieldMust === 2) {
              col.isrequired = true
              col.validateRules = [
                {
                  required: true, // 必填
                  message: `${field.fieldName}不能为空`, // 提示的文本
                },
              ]
            }
            if(field.fieldMust === 1){
              col.disabled = true
            }

            // 这里根据自定义字段的类型，设置为普通文本输入还是数字输入
            if (field.fieldType == 1) {
              col.type = FormTypes.input
            } else if (field.fieldType == 2) {
              col.type = FormTypes.input
            } else if (field.fieldType == 3) {
              col.type = FormTypes.inputNumber
              const maxLength = field.fieldLength // 获取最大长度变量的值
              const pattern = new RegExp(`^\\d{1,${maxLength}}$`)
              if (!(col.validateRules && col.validateRules.length)) {
                col.validateRules = []
              }
              col.validateRules.push({
                pattern: pattern,
                message: `最大长度为${maxLength}`,
              })
            }
            else{
              col.type = FormTypes.inputNumber
              const maxLength = field.fieldLength // 获取最大长度变量的值
              const pattern = new RegExp(`^\\d{1,${maxLength}}(\\.\\d{1,${maxLength - 1}})?$`)
              if (!(col.validateRules && col.validateRules.length)) {
                col.validateRules = []
              }
              col.validateRules.push({
                pattern: pattern,
                message: `最大长度为${maxLength}`,
              })
            }
            columns.push(col)
          })
          
          this.processTable.columns = [...goodsColumns, ...columns]
        }
      })
    },
    goodChange(item) {
      this.form.goodsSpec = item.spec
      this.form.goodsTypeName = item.type
      this.form.goodsTypeNameText = item.typeText
      this.form.basicUnit = item.basicUnit
      this.form.basicUnitText = item.basicUnitText
      this.form.goodsId = this.goodsValue
      this.form.goodsCodeName = `${item.goodsCode}-${item.goodsName}`
      this.$refs['ruleFormTwo'].validateField(['goodsId'])
      let craftObj = {
        pageNo: this.craft_pageNo,
        pageSize: this.craft_pageSize,
        goodsId: this.form.goodsId,
      }
      queryOptionList(craftObj).then((res) => {
        if (res.success) {
          this.craftList = res.result.records
          this.form.craftId = undefined
          if (res.result.total && res.result.total === 1) {
            // 若选中的产品关联了工艺路线，则优先默认把工艺路线的信息回填到子表
            this.form.craftId = this.craftList[0].value
            this.craftText = this.craftList[0].text
            this.craftValue = this.craftList[0].value
            this.craftChange(this.form.craftId)
          } else {
            // 若没有关联工艺路线，且物料分类只关联了一个生产流程，则默认把对应生产流程的信息回填到子表
            this.$refs.craftPath.initialize()
            this.getGoodsFlow()
          }
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
      let inventoryObj = {
        pageNo: 1,
        pageSize: 999,
        goodsId: this.form.goodsId,
      }
      this.inventoryParams.loading = true
      inventoryApi(inventoryObj).then((res) => {
        if (res.success) {
          if (res.result) {
            let newArr = res.result.records
            newArr = newArr.map((item) => {
              if (this.form.num) {
                item.planTotalNum =
                  Number(this.form.num) *
                  (Number(item.basicUseLevel) + Number(item.basicUseLevel) * Number(item.loss / 100))
                return item
              } else {
                return item
              }
            })
            console.log(newArr)
            this.inventoryParams.dataSource = newArr
          } else {
            this.inventoryParams.dataSource = []
            // this.$antdMessage.warning('该产品BOM未配置')
          }
        } else {
          this.$antdMessage.warning(res.message)
        }
        this.inventoryParams.loading = false
      })
      this.$forceUpdate()
    },
    getSelectValue(id, text, item) {
      this.form.setFieldsValue({
        processRouteId: id,
        processRouteIdText: text,
      })
    },
    // 选择合格品单位
    qualifiedChange(e, props, key) {
      let { unitList, rateQOld, inventoryGoodsQualifiedNum } = this.$refs[key].getValuesSync({
        validate: false,
        rowIds: [props.rowId],
      }).values[0]
      // console.log('inventoryGoodsQualifiedNum:',inventoryGoodsQualifiedNum,'-','rateQOld:',rateQOld);
      let old_num = inventoryGoodsQualifiedNum
        ? accMul(inventoryGoodsQualifiedNum, rateQOld)
        : '' /* 当前数值乘以单位换算比例，得到对应的基本单位数量 */
      let unit = JSON.parse(unitList).find((item) => item.id == e)
      this.$refs[key].setValues([
        {
          rowKey: props.rowId,
          values: {
            rateQ: unit.conversionRate,
            rateQOld: unit.conversionRate,
            selectUnitQ: e,
            inventoryGoodsQualifiedNum: inventoryGoodsQualifiedNum
              ? accDivMin(old_num, unit.conversionRate)
              : '' /* 基本单位数量除以辅助单位比例，得到当前数值对应辅助单位数量 */,
          },
        },
      ])
    },
    // 选择报废品单位
    scrapNumChange(e, props, key) {
      let { unitList, rateSOld, inventoryGoodsScrapNum } = this.$refs[key].getValuesSync({
        validate: false,
        rowIds: [props.rowId],
      }).values[0]
      let old_num = inventoryGoodsScrapNum ? accMul(inventoryGoodsScrapNum, rateSOld) : ''
      let unit = JSON.parse(unitList).find((item) => item.id == e)
      this.$refs[key].setValues([
        {
          rowKey: props.rowId,
          values: {
            rateS: unit.conversionRate,
            rateSOld: unit.conversionRate,
            selectUnitS: e,
            inventoryGoodsScrapNum: inventoryGoodsScrapNum ? accDivMin(old_num, unit.conversionRate) : '',
          },
        },
      ])
    },
    dataSourceItem(props, key, ediKey) {
      let item = this.$refs[ediKey].getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      let val = item[key]
      if (key == 'unitList') {
        return JSON.parse(val)
      } else {
        return val
      }
    },
    closeBtn() {
      this.jkeForm.visible = false
      // this.submitProcess()
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (e && e.nodeDtos) {
        this.processDataVo = e
        // console.log(e, this.processDataVo, 'processDataVo')
        // 获取到数据后写表单提交的方法
        this.saveForm(this.sendType)
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },
    // tab分页
    changeCurrent(key) {
      if (key == '1') {
        // this.selectRowKeys = []
        this.addOrEdit = false
        // this.getAbleTableList() //已盘点
      } else {
        // this.selectRowKeys = []
        this.addOrEdit = true // 待盘点
        // this.getEditUnAbleTable()
      }
      //   this.getData()
    },
    // 分页
    onChangePage(current, pageSize) {
      this.getGoodsListPage.current = current
      if (this.queryId) {
        this.getEditUnAbleTable()
      } else {
        this.getGoodsList()
      }
    },
    onShowSizeChange(current, pageSize) {
      this.getGoodsListPage.pageSize = pageSize
      this.getGoodsListPage.current = current
      if (this.queryId) {
        this.getEditUnAbleTable()
      } else {
        this.getGoodsList()
      }
    },

    selectRowChange(ids) {
      this.selectRowKeys = ids
      if (this.selectRowKeys.length !== 0) {
        this.selectRowKeys.forEach((item) => {
          var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [item] }).values[0]
          if (!tableValue.inventoryGoodsQualifiedNum && !tableValue.inventoryGoodsScrapNum) {
            this.$refs.goodsTable.setValues([
              {
                rowKey: item, // 行的id
                values: {
                  // 在这里 values 中的 specifications 是你 columns 中配置的 key
                  inventoryGoodsQualifiedNum: tableValue.goodsQualifiedNum
                    ? accDivMin(tableValue.goodsQualifiedNum, tableValue.rateQ)
                    : '',
                  inventoryGoodsScrapNum: tableValue.goodsScrapNum
                    ? accDivMin(tableValue.goodsScrapNum, tableValue.rateS)
                    : '',
                  pdAmountExcludingTax: tableValue.amountExcludingTax,
                },
              },
            ])
          }
        })
      }
    },
    validateunitName(value, callback) {
      if (this.isEdit && this.queryParam.processesName == value) {
        callback()
        return false
      }
      APILX.basicProductionProcessesQueryByProcessesName({ processesName: value }).then((res) => {
        console.log(res)

        !res.result ? callback() : callback('单位值不能重复')
      })
    },

    // 工序弹窗事件-----end
    searchResetGoods() {
      this.filterForm.goodsCode = ''
      this.filterForm.goodsName = ''
      this.$refs.tableSelect.searchReset()
    },
    searchGoods() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    // 产品下拉改弹窗
    openIt() {
      let par = {
        list: '/basicprocess/basicProcessRouteInfo/list',
        visible: true, //弹窗开启
        title: '工艺路线', //标题名称
        multi: false, //是否多选
        columns: this.columns, //表格配置
        value: this.goodsValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.goodsText, //回显的中文，如：'张三'
        textKey: 'processRouteName', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    // 待盘点
    getEditUnAbleTable() {
      let param = {
        id: this.queryId,
        warehouseId: this.warehouseIdEdit,
        pageNo: this.getGoodsListPage.current,
        pageSize: this.getGoodsListPage.pageSize,
      }
      this.goodsTable.dataSource = []
      this.isLoading = true
      // console.log(this.isLoading, ' getEditUnAbleTable isLoadingisLoadingisLoading')
      APILX.warehouseInventoryUnCompleteList(param).then(async (res) => {
        if (res.code == 200) {
          // console.log(res, '进来了没warehouseInventoryUnCompleteList')
          let tableData = res.result.records
          for (let i = 0; i < tableData.length; i++) {
            let item = tableData[i]
            const unitRes = await API.findUnitListByGoodsIdSync({ goodsId: item.goodsId })
            item.unitList = JSON.stringify(unitRes.result)
            item.rateQ = 1
            item.rateS = 1
            item.rateQOld = 1
            item.rateSOld = 1
            item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id
            item.selectUnitS = unitRes.result[unitRes.result.length - 1].id
          }
          tableData.forEach((item) => {
            if (item.attachment) {
              let ids = item.attachment
              getFileListByIds({ ids }).then((res) => {
                if (res.code == 200) {
                  let fileList = ''
                  fileList = res.result
                  if (fileList.length > 0) {
                    item.picUrl = this.domianURL + fileList[0].uri
                    this.goodsTable.dataSource.push(item)
                  } else {
                    item.picUrl = require('../../../assets/img/noPicture.jpg')
                    this.goodsTable.dataSource.push(item)
                  }
                }
              })
            } else {
              item.picUrl = require('../../../assets/img/noPicture.jpg')
              this.goodsTable.dataSource.push(item)
            }
          })
          // this.goodsTable.dataSource = tableData
          console.log(this.goodsTable.dataSource, 'this.goodsTable.dataSource')
          this.getGoodsListPage.total = res.result.total
          setTimeout(() => {
            this.isLoading = false
          }, 1000)
        } else {
          this.$antdMessage.error(res.message)
          this.isLoading = false
        }
      })
    },
    //已盘点 table
    // 分页
    onChangePageEd(current, pageSize) {
      this.getGoodsListPageEd.current = current
      this.getAbleTableList()
    },
    onShowSizeChangeEd(current, pageSize) {
      this.getGoodsListPageEd.pageSize = pageSize
      this.getGoodsListPageEd.current = current
      this.getAbleTableList()
    },

    selectRowChangeEd(ids) {
      this.selectRowKeysEd = ids
      console.log(this.selectRowKeysEd, 'selectRowChangeEd')
      if (this.selectRowKeysEd.length !== 0) {
        this.selectRowKeysEd.forEach((item) => {
          var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [item] }).values[0]
          this.selectGoodsIdsEd.push(tableValue.goodsId)
          if (!tableValue.inventoryGoodsQualifiedNum && !tableValue.inventoryGoodsScrapNum) {
            this.$refs.goodsTableEd.setValues([
              {
                rowKey: item, // 行的id
                values: {
                  // 在这里 values 中的 specifications 是你 columns 中配置的 key
                  // inventoryGoodsQualifiedNum: tableValue.goodsQualifiedNum || '',
                  // inventoryGoodsScrapNum: tableValue.goodsScrapNum || '',
                  inventoryGoodsQualifiedNum: tableValue.goodsQualifiedNum
                    ? accDivMin(tableValue.goodsQualifiedNum, tableValue.rateQ)
                    : '',
                  inventoryGoodsScrapNum: tableValue.goodsScrapNum
                    ? accDivMin(tableValue.goodsScrapNum, tableValue.rateS)
                    : '',
                },
              },
            ])
          }
        })
      }
    },
    // 已盘点 编辑
    getAbleTableList() {
      console.log('selectRowKeysEd', this.selectGoodsIdsEd)
      let param = {
        id: this.queryId,
        pageNo: this.getGoodsListPageEd.current,
        pageSize: this.getGoodsListPageEd.pageSize,
      }
      this.goodsTableEd.dataSource = []
      this.isLoading = true
      // console.log(this.isLoading, ' getAbleTableList isLoadingisLoadingisLoading')
      APILX.wmsWarehouseInventoryCompleteList(param).then(async (res) => {
        if (res.code == 200) {
          // console.log(res, '进来了没warehouseInventoryUnCompleteList')
          let tableData = res.result.records
          for (let i = 0; i < tableData.length; i++) {
            let item = tableData[i]
            const unitRes = await API.findUnitListByGoodsIdSync({ goodsId: item.goodsId })
            item.unitList = JSON.stringify(unitRes.result)
            if (item.goodsQualifiedUnitId) {
              let unitQ = unitRes.result.find((u) => u.id == item.goodsQualifiedUnitId)
              let unitS = unitRes.result.find((u) => u.id == item.goodsScrapUnitId)
              item.selectUnitQ = unitQ ? unitQ.id : unitRes.result[unitRes.result.length - 1].id
              item.selectUnitS = unitS ? unitS.id : unitRes.result[unitRes.result.length - 1].id

              item.rateQ = unitQ ? unitQ.conversionRate : 1
              item.rateQOld = unitQ ? unitQ.conversionRate : 1

              item.rateS = unitS ? unitS.conversionRate : 1
              item.rateSOld = unitS ? unitS.conversionRate : 1

              item.inventoryGoodsQualifiedNum = accDivMin(item.inventoryGoodsQualifiedNum, item.rateQ)
              item.inventoryGoodsScrapNum = accDivMin(item.inventoryGoodsScrapNum, item.rateS)
            } else {
              item.rateQ = 1
              item.rateS = 1
              item.rateQOld = 1
              item.rateSOld = 1
              item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id
              item.selectUnitS = unitRes.result[unitRes.result.length - 1].id
            }
          }
          tableData.forEach((item) => {
            if (item.attachment) {
              let ids = item.attachment
              getFileListByIds({ ids }).then((res) => {
                if (res.code == 200) {
                  let fileList = ''
                  fileList = res.result
                  if (fileList.length > 0) {
                    item.picUrl = this.domianURL + fileList[0].uri
                    this.goodsTableEd.dataSource.push(item)
                  } else {
                    item.picUrl = require('../../../assets/img/noPicture.jpg')
                    this.goodsTableEd.dataSource.push(item)
                  }
                }
              })
            } else {
              item.picUrl = require('../../../assets/img/noPicture.jpg')
              this.goodsTableEd.dataSource.push(item)
            }
            if (item.inventoryGoodsQualifiedNum == '-') {
              item.inventoryGoodsQualifiedNum = 0.0
            }
            if (item.inventoryGoodsScrapNum == '-') {
              item.inventoryGoodsScrapNum = 0.0
            }
          })
          this.getGoodsListPageEd.total = res.result.total
          let _that = this
          setTimeout(() => {
            _that.isLoading = false
            console.log(_that.selectGoodsIdsEd, 'this.goodsTableEd.dataSource')
            const { error, values } = _that.$refs.goodsTableEd.getValuesSync({ validate: false })
            let ids = []
            let goods = values.filter((item) => _that.selectGoodsIdsEd.includes(item.goodsId))
            // console.log('aaaaaa',aaa);
            for (let g = 0; g < goods.length; g++) {
              ids.push(goods[g].id)
            }
            _that.$refs.goodsTableEd.setSelection(ids)
          }, 1000)
          // this.isLoading = false
        } else {
          this.$antdMessage.error(res.message)
          this.isLoading = false
        }
      })
    },

    /* 获取编辑详情 */
    async initForm(v, copy = false) {
      this.getExtended()
      await this.getDic()
      this.jkeForm.visible = true
      this.processTable.dataSource = []

      APILX.warehouseOutboundOrderInfoEntryType().then((res) => {
        this.outWarehouseType = JSON.parse(JSON.stringify(res.result))
      })
      if (v) {
        this.queryParam = v

        if (copy) {
          this.isEdit = false
          this.submitApi = APILX.warehouseOutboundOrderInfoAdd
          this.queryId = null
          this.jkeForm.title = '新建出库单'
        } else {
          this.submitApi = APILX.warehouseOutboundOrderInfoEdit
          this.isEdit = true
          this.queryId = v.id
          this.jkeForm.title = '编辑出库单'
          // debugger
          APILX.warehouseEntryDetailList({ entryId: this.queryId, inOutType: 1 }).then((res) => {
            if (res.code == 200) {
              this.processTable.dataSource = res.result.records.map((ele) => {
                let newkey = ''
                let newObj = {}
                for (const key in ele.extDataJson) {
                  newkey = 'extDataJson.' + key
                  newObj[newkey] = ele.extDataJson[key]
                }
                return {
                  ...ele,
                  ...newObj,
                  serialNumber: ele.inWarehouseNum,
                  serialCode: ele.serialNumber,
                  id: ele.serialId,
                }
              })
            } else {
              this.$antdMessage.error(res.message)
            }
          })
        }
        // console.log(id, '00.0.0.0')

        let _this = this
        setTimeout(() => {
          for (const key in v.extDataJson) {
            let newkey = 'extDataJson.' + key
            v[newkey] = v.extDataJson[key]
          }
          _this.form.setFieldsValue({
            ...v,
            outWarehouseTimeText: v.outWarehouseTime,
            produceOrderName: v.produceOrderCode,
            saleOrderCode: v.saleOrderCode,
          })
          this.$refs.createFormItemRef.setFields({ ...v, outWarehouseTimeText: v.outWarehouseTime })
        }, 300)
      } else {
        this.jkeForm.title = '新建出库单'
        this.isEdit = false
        this.submitApi = APILX.warehouseOutboundOrderInfoAdd
        this.queryId = null
        setTimeout(() => {
          let currentLogin = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value
          let inWarehouseType = this.outWarehouseType.find((item) => item.itemText === '生产出库').itemValue
          this.form.setFieldsValue({
            outWarehouseType: inWarehouseType,
            receiverPersion: currentLogin.id,
            receiverPersionName: currentLogin.realname,
            outWarehouseTime: this.getCurrentData,
            outWarehouseTimeText: this.getCurrentData,
          })
        }, 1200)
      }
    },

    // 提交
    saveForm(all) {
      this.handleSubmit([], all)
    },
    // 提交
    saveFormEd(newparam1, all) {
      // console.log(all, 'all')
      if (this.selectRowKeysEd.length !== 0) {
        const { error, values } = this.$refs.goodsTableEd.getValuesSync({ validate: true })
        let newparamEd = values.filter((item) => this.selectRowKeysEd.includes(item.id))
        //合并两个数组
        let newparam = newparam1.concat(newparamEd)
        // console.log(newparam, 'newparam')
        this.handleSubmit(newparam, all)
      } else {
      }
      this.handleSubmit(newparam1, all)

      // console.log(all, 'all2')
    },
    // handleSubmit(tableValue, all) {
    //   this.form.validateFields((err, values) => {
    //     console.log(values, 'values form')
    //     if (!err) {
    //       this.submitTo(tableValue, values, all)
    //     }
    //   })
    // },
    handleSubmit(tableValue, all) {
      this.form.validateFields((err, values) => {
        if (!err) {
          // 自定义信息表单验证
          this.$refs.createFormItemRef.form.validateFields((err, value) => {
            if (!err) {
              let subForm = {
                ...values,
                ...value,
              }
              this.submitTo(tableValue, subForm, all)
            } else {
              return
            }
          })
        }
      })
    },
    submitTo(tableValue, values, all) {
      const { error, values: tableValues } = this.$refs.processTable.getValuesSync({ validate: true })

      if (tableValues && tableValues.length == 0) {
        this.$antdMessage.warning('出库物品明细不可为空!')
        return
      } else {
        if (error != 0) {
          return
        }
      }

      let parameters = {
        ...values,
        entryDetails: tableValues.map((item) => {
          let extDataJson = {}
          for (const key in item) {
            if (Object.hasOwnProperty.call(item, key)) {
              const value = item[key]
              if (key.includes('extDataJson')) {
                let keys = key.split('.')
                extDataJson[keys[1]] = value
              }
            }
          }

          console.log(tableValues)
          debugger

          return {
            entryId: this.queryId || undefined,
            serialId: item.id,
            inWarehouseNum: item.serialNumber,
            extDataJson,
          }
        }),
        id: this.queryId || null,
      }

      this.loadingSubmit = true
      this.submitApi(parameters).then((res) => {
        if (res.code == 200) {
          this.loadingSubmit = false
          let subMsg = this.isEdit ? '编辑出库单成功！' : '新建出库单成功！'
          this.$antdMessage.success(subMsg)
          this.goBack()
        } else {
          this.loadingSubmit = false
          this.$antdMessage.error(res.message)
        }
      })
    },
    submitAll(tableValue, values, all) {
      let that = this
      that.$antdConfirm({
        title: '确定盘点完毕吗?',
        content: `盘点完毕后，无法更改盘点数据`,
        onOk() {
          // console.log(all, 'all 弹窗')
          that.submitTo(tableValue, values, all)
        },
        onCancel() {},
      })
    },
    setColor(props) {
      // if (props.text == 0) {
      //   return '#0f0!important'
      // }
      var newNum = props.text
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      // console.log(tableValue, 'tableValuetableValuetableValue')
      if (Number(newNum) > tableValue.goodsQualifiedNum) {
        return '#ff4d4f'
      } else {
        return '#00b042'
      }
    },
    setColor2(props) {
      var newNum = props.text
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (Number(newNum) > tableValue.goodsScrapNum) {
        return '#ff4d4f'
      } else {
        return '#00b042'
      }
    },

    inputNum(e, props, inputKey) {
      let newNum = fourFloatNum(e.target.value)
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (inputKey == 'inventoryGoodsQualifiedNum') {
        if (Number(newNum) > tableValue.goodsQualifiedNum) {
          // this.$antdMessage.warning('库存不足：本次盘点合格品不得大于账面合格品')
        } else {
        }
      }
      if (inputKey == 'inventoryGoodsScrapNum') {
        if (Number(newNum) > tableValue.goodsScrapNum) {
          // this.$antdMessage.warning('库存不足：本次盘点报废品不得大于账面报废品')
        } else {
        }
      }
      this.$refs.goodsTable.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            [inputKey]: newNum,
          },
        },
      ])
      // var tableValue2 = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      // console.log(tableValue2, 'tableValue2tableValue2')
    },
    pdMoney(val, props, tableType) {
      this.$refs[tableType].setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            pdAmountExcludingTax: val,
          },
        },
      ])
    },
    inputFocus(props) {
      // console.log(props, 'props')
      const isSelect = this.selectRowKeys.filter((each) => each == props.rowId)
      if (isSelect.length == 0) {
        // this.selectRowKeys.push(props.rowId)
        this.$antdMessage.error('请先勾选当前数据')
        // console.log(this.selectRowKeys, 'this.selectRowKeys')
      }
    },

    // 已盘点
    inputFocusEd(props) {
      // console.log(props, 'props')
      const isSelect = this.selectRowKeysEd.filter((each) => each == props.rowId)
      if (isSelect.length == 0) {
        // this.selectRowKeysEd.push(props.rowId)
        this.$antdMessage.error('请先勾选当前数据')
        // console.log(this.selectRowKeysEd, 'this.selectRowKeysEd')
      }
    },
    setColorEd(props) {
      // console.log(props.text)
      // if (props.text == 0) {
      //   return '#0f0!important'
      // }
      var newNum = props.text
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      // console.log(tableValue, 'tableValuetableValuetableValue')
      if (Number(newNum) > tableValue.goodsQualifiedNum) {
        return '#ff4d4f'
      } else {
        return '#00b042'
      }
    },
    setColor2Ed(props) {
      var newNum = props.text
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (Number(newNum) > tableValue.goodsScrapNum) {
        return '#ff4d4f'
      } else {
        return '#00b042'
      }
    },

    inputNumEd(e, props, inputKey) {
      let newNum = fourFloatNum(e.target.value)
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (inputKey == 'inventoryGoodsQualifiedNum') {
        if (Number(newNum) > tableValue.goodsQualifiedNum) {
          // this.$antdMessage.warning('库存不足：本次盘点合格品不得大于账面合格品')
        } else {
        }
      }
      if (inputKey == 'inventoryGoodsScrapNum') {
        if (Number(newNum) > tableValue.goodsScrapNum) {
          // this.$antdMessage.warning('库存不足：本次盘点报废品不得大于账面报废品')
        } else {
        }
      }
      this.$refs.goodsTableEd.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            [inputKey]: newNum,
          },
        },
      ])
      // var tableValue2 = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      // console.log(tableValue2, 'tableValue2tableValue2')
    },

    // 已盘点结束

    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'WMS_GOODS' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            inventoryCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    valueChange(type, row) {
      // console.log(type, row, 'value change type')
    },
    //   选仓库带明细
    selectOrder(v) {
      if (v) {
        this.getGoodsId = v
        this.getGoodsList()
      }
    },
    getGoodsList() {
      let param = {
        id: this.getGoodsId,
        pageNo: this.getGoodsListPage.current,
        pageSize: this.getGoodsListPage.pageSize,
      }
      this.goodsTable.dataSource = []
      this.isLoading = true
      APILX.getGoodsListByWarehouseId(param).then(async (res) => {
        if (res.result) {
          let tableData = res.result.records
          for (let i = 0; i < tableData.length; i++) {
            let item = tableData[i]
            const unitRes = await API.findUnitListByGoodsIdSync({ goodsId: item.goodsId })
            item.unitList = JSON.stringify(unitRes.result)
            item.rateQ = 1
            item.rateS = 1
            item.rateQOld = 1
            item.rateSOld = 1
            item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id
            item.selectUnitS = unitRes.result[unitRes.result.length - 1].id
          }
          tableData.forEach((item) => {
            // const unitRes = await API.findUnitListByGoodsIdSync({goodsId: item.goodsId})
            // item.unitList = JSON.stringify(unitRes.result)
            // item.rateQ = 1
            // item.rateS = 1
            // item.selectUnitQ = unitRes.result[unitRes.result.length-1].id
            // item.selectUnitS = unitRes.result[unitRes.result.length-1].id
            if (item.attachment) {
              let ids = item.attachment
              getFileListByIds({ ids }).then((res) => {
                if (res.code == 200) {
                  let fileList = ''
                  fileList = res.result
                  if (fileList.length > 0) {
                    item.picUrl = this.domianURL + fileList[0].uri
                    this.goodsTable.dataSource.push(item)
                  } else {
                    item.picUrl = require('../../../assets/img/noPicture.jpg')
                    this.goodsTable.dataSource.push(item)
                  }
                }
              })
            } else {
              item.picUrl = require('../../../assets/img/noPicture.jpg')
              this.goodsTable.dataSource.push(item)
            }
          })
          // console.log(this.goodsTable.dataSource, 'this.goodsTable.dataSource')
          this.getGoodsListPage.total = res.result.total
          this.tabNor = `待盘点（${this.getGoodsListPage.total}）`
          this.isLoading = false
        }
      })
    },
    /* 面包屑返回 */
    goBack() {
      this.$emit('refresh')
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      // console.log('上传的附件id：', v)
    },
    /* 选盘点人 */
    userFilter(v, row) {
      // console.log(v, row)
      this.form.setFieldsValue({
        inventoryUserId: v,
      })
      if (row.length > 0) {
        this.signUser = row[0].id
      } else {
        this.signUser = ''
      }
    },
    // 下拉搜索
    filterOption(input, option) {
      // console.log('inputoption', input, option)
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    cancel() {},
    setGoodsScrapNum(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsScrapNum) {
        return tableValue.goodsScrapNum
      } else {
        return ''
      }
    },
    setUnit(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.assistUnit) {
        return tableValue.assistUnit
      } else {
        return ''
      }
    },
    setSpec(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.spec) {
        return tableValue.spec
      } else {
        return '-'
      }
    },
    setName(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsName) {
        return tableValue.goodsName
      } else {
        return ''
      }
    },
    setCode(props) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsCode) {
        return tableValue.goodsCode
      } else {
        return ''
      }
    },

    // 已盘点
    setGoodsScrapNumEd(props) {
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsScrapNum) {
        return tableValue.goodsScrapNum
      } else {
        return ''
      }
    },
    // 辅助单位账面库存数量
    setNumAssistUnit(props, key, numTextKey) {
      var tableValue = this.$refs[key].getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      // console.log('setNumAssistUnit', tableValue)
      // return tableValue.goodsScrapNumTextAssistUnit || '-'
      return tableValue[numTextKey] || '-'
    },
    setUnitEd(props) {
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.assistUnit) {
        return tableValue.assistUnit
      } else {
        return ''
      }
    },
    setSpecEd(props) {
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.spec) {
        return tableValue.spec
      } else {
        return ''
      }
    },
    setNameEd(props) {
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsName) {
        return tableValue.goodsName
      } else {
        return ''
      }
    },
    setCodeEd(props) {
      var tableValue = this.$refs.goodsTableEd.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      if (tableValue.goodsCode) {
        return tableValue.goodsCode
      } else {
        return ''
      }
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';

.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}

/deep/ .ant-form-vertical {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;

  .ant-form-item {
    width: 30%;
  }
}

.form-body {
  height: calc(100vh - 110px);
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
  align-items: center;
  justify-content: center;
}

.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}

.pic-f {
  box-sizing: border-box;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 20px 10px;

  .pic-r {
    flex: 1;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #444444;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    .subDiv {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.imgClass {
  width: 60px;
  height: 60px;
  border-radius: 6px;
}

.my-input {
  padding: 4px 30px 4px 11px;
  border-radius: 3px;
  border: solid 1px #cdcdcd;
}

input::-webkit-input-placeholder {
  color: #cdcdcd;
}

input::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: #cdcdcd;
}

input:-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  color: #cdcdcd;
}

input:-ms-input-placeholder {
  /* Internet Explorer 10-11 */
  color: #cdcdcd;
}

/deep/ .ant-card-body {
  padding: 20px 24px;
}
</style>
